package com.sy.util;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class POP3MailUtil {

    static Folder folder;
    static Store store;

    public static void receive() {
        for(File file:getAllProties()){
            if(!file.isDirectory()){
                try {
                    // 准备连接服务器的会话信息
                    Properties props = new Properties();
                    InputStream inputStream = new FileInputStream(file.getPath());
                    props.load(inputStream);
                    // 创建Session实例对象
                    Session session = Session.getInstance(props);

                    store = session.getStore("pop3");
                    store.connect(props.getProperty("mail.user"), props.getProperty("mail.password")); //163邮箱程序登录属于第三方登录所以这里的密码是163给的授权密码而并非普通的登录密码
                    // 获得收件箱
                    folder = store.getFolder("INBOX");
                    folder.open(Folder.READ_WRITE); //打开收件箱

                    // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
                    System.out.println("未读邮件数: " + folder.getUnreadMessageCount());
                    // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
                    System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
                    System.out.println("新邮件: " + folder.getNewMessageCount());
                    // 获得收件箱中的邮件总数
                    System.out.println("邮件总数: " + folder.getMessageCount());

                    // 得到收件箱中的所有邮件,并解析
                    Message[] messages = folder.getMessages();
                    parseMessage(messages);
                } catch (NoSuchProviderException e) {
                    e.printStackTrace();
                } catch (MessagingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void close() {
        try {
            folder.close(true);
            store.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析邮件
     * @param messages 要解析的邮件列表
     */
    public static void parseMessage(Message ...messages) throws MessagingException, IOException {
        if (messages == null || messages.length < 1)
            throw new MessagingException("未找到要解析的邮件!");

        // 解析所有邮件
//        for (int i = 0, count = messages.length; i < count; i++) {
//            MimeMessage msg = (MimeMessage) messages[i];
//            System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
//            System.out.println("主题: " + getSubject(msg));
//            System.out.println("发件人: " + getFrom(msg));
//            System.out.println("收件人：" + getReceiveAddress(msg, null));
//            System.out.println("发送时间：" + getSentDate(msg, null));
//            System.out.println("是否已读：" + isSeen(msg));
//            System.out.println("邮件优先级：" + getPriority(msg));
//            System.out.println("是否需要回执：" + isReplySign(msg));
//            System.out.println("邮件大小：" + msg.getSize() * 1024 + "kb");
//            boolean isContainerAttachment = isContainAttachment(msg);
//            System.out.println("是否包含附件：" + isContainerAttachment);
//            if (isContainerAttachment) {
////                saveAttachment(msg, "f:\\mailTest\\"+msg.getSubject() + "_"+i+"_"); //保存附件
//            }
//            if (!isSeen(msg)) {
//                seen(msg);
//                System.out.println("再次确认是否已读：" + isSeen(msg));
//            }
//            StringBuffer content = new StringBuffer(30);
//            getMailTextContent(msg, content);
//            System.out.println("邮件正文：" + (content.length() > 100 ? content.substring(0,100) + "..." : content));
//            System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
//            System.out.println();

//        }
    }

    public static void seen (MimeMessage msg) throws MessagingException {
        msg.setFlag(Flags.Flag.SEEN, true);
    }

    public static File[] getAllProties() {
        String path = Const.MailPath.popPath;
        File[] files = new File(path).listFiles();	//遍历path下的文件和目录，放在File数组中
        return files;
    }
}
